from marshmallow import Schema, fields, validate, validates, ValidationError
import re
from datetime import datetime

class ContactInfoSchema(Schema):
    """联系信息模式"""
    phone = fields.Str(required=True)
    address = fields.Str()
    emergencyContact = fields.Str()

    def validate_phone(self, value, **kwargs):
        """验证手机号格式"""
        if value and not re.match(r'^\d{11}$', value):
            raise ValidationError('手机号格式不正确')
        return value

class MedicalInfoSchema(Schema):
    """医疗信息模式"""
    bloodType = fields.Str(validate=validate.OneOf(['A', 'B', 'AB', 'O', 'A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-', '未知']))
    allergies = fields.List(fields.Str())
    chronicDiseases = fields.List(fields.Str())

class InsuranceInfoSchema(Schema):
    """保险信息模式"""
    provider = fields.Str()
    policyNumber = fields.Str()
    expiryDate = fields.Date()

class PatientSchema(Schema):
    """患者模式"""
    patientId = fields.Str()
    name = fields.Str(required=True)
    gender = fields.Str(required=True, validate=validate.OneOf(['男', '女', '其他']))
    birthDate = fields.Date(required=True)
    idNumber = fields.Str(required=True)
    contactInfo = fields.Nested(ContactInfoSchema, required=True)
    medicalInfo = fields.Nested(MedicalInfoSchema)
    registrationDate = fields.DateTime(dump_default=datetime.utcnow)
    insuranceInfo = fields.Nested(InsuranceInfoSchema)
    tags = fields.List(fields.Str())
    activeStatus = fields.Boolean(dump_default=True)

    def validate_id_number(self, value, **kwargs):
        """验证身份证号格式"""
        if value and not re.match(r'^\d{17}[\dXx]$', value):
            raise ValidationError('身份证号格式不正确')
        return value

class PatientUpdateSchema(Schema):
    """患者更新模式"""
    name = fields.Str()
    gender = fields.Str(validate=validate.OneOf(['男', '女', '其他']))
    birthDate = fields.Date()
    idNumber = fields.Str()
    contactInfo = fields.Nested(ContactInfoSchema)
    medicalInfo = fields.Nested(MedicalInfoSchema)
    insuranceInfo = fields.Nested(InsuranceInfoSchema)
    tags = fields.List(fields.Str())
    activeStatus = fields.Boolean()

    def validate_id_number(self, value, **kwargs):
        """验证身份证号格式"""
        if value and not re.match(r'^\d{17}[\dXx]$', value):
            raise ValidationError('身份证号格式不正确')
        return value 